<?php

require_once('Zabbix.php');

/**
 *
 */
class Zabbix_Sensor_Apache extends Zabbix_Sensor {

    protected $_uri = '/server-status?auto';

    protected $_attributes = array();

    protected function parseAttribute($line) {
        if ( strpos($line, ':') > 0 ) {
            list($name, $value) = explode(':', $line, 2);
            $this->setAttribute($name, $value);
        }
    }

    protected function makeStatusRequest($host = '127.0.0.1', $port = 80, $parseScore = true) {
        $url = 'http://' . $host . ':' . $port . $this->_uri;
        echo $url;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// allow redirects
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
        curl_setopt($ch, CURLOPT_TIMEOUT, 3); // times out after 4s
        $result = curl_exec($ch); // run the whole process
        curl_close($ch);  

        $lines = explode("\n", $result);
        foreach($lines as $line) {
            $this->parseAttribute($line);
        }

        if ( $parseScore ) {
            $this->getScore();
        }
    }

    /**
     *
     *
     */
    public function init() {

        $host = $this->getOption('host', '127.0.0.1');
        $port = $this->getOption('port', '80');
        $parseScore = true;

        // ...
        $this->makeStatusRequest($host, $port, $parseScore);
    }

    public function getAttribute($name) {
        $result = null;
        if (array_key_exists($name, $this->_attributes)) {
            $result = $this->_attributes[$name];
        }
        return $result;
    }

    public function setAttribute($name, $value) {
        $this->_attributes[$name] = $value;
    }

    public function getAttributes() {
        return $this->_attributes;
    }

    /**
     *
     */
    public function getScore() {
        // "_" Waiting for Connection,
        // "S" Starting up,
        // "R" Reading Request,
        // "W" Sending Reply,
        // "K" Keepalive (read),
        // "D" DNS Lookup,
        // "C" Closing connection,
        // "L" Logging,
        // "G" Gracefully finishing,
        // "I" Idle cleanup of worker,
        // "." Open slot with no current process

        $score = $this->getAttribute('Scoreboard');

        $waitingForConnection = substr_count($score, '_');
        $this->setAttribute('Waiting for connection', $waitingForConnection);

        $sendingReply = substr_count($score, 'W');
        $this->setAttribute('Sending Reply', $sendingReply);

        // Open slot with no current process
        $openSlot = substr_count($score, '.');
        $this->setAttribute('Open slot with no current process', $openSlot);

    }

}
